package com.itzhoun.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itzhoun.entity.SysJob;
import com.itzhoun.service.JobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 定时任务调度
 *
 * @author 周楠
 * @Date 2022/08/15/下午 11:38
 */
@Api("添加定时任务")
@RestController
@RequestMapping("/quartz/job")
public class SysJobController {

    @Resource
    private JobService jobService;


    @ApiOperation("查询任务列表")
    @GetMapping("/page")
    public IPage<SysJob> sysJobIPage(SysJob sysJob) {
        return jobService.page(new Page<>(1, 10), new QueryWrapper<SysJob>()
                .like(StringUtils.isNotBlank(sysJob.getJobName()), "job_name", sysJob.getJobName())
                .eq(StringUtils.isNotBlank(sysJob.getJobGroup()), "job_group", sysJob.getJobGroup()));
    }

    @ApiOperation("获取定时任务详细信息")
    @GetMapping("/{jobId}")
    public SysJob getSysJobDetail(@PathVariable("jobId") Long jobId) {
        return jobService.getById(jobId);
    }


    /**
     * 新增定时任务
     *
     * @param sysJob
     * @return
     */
    @ApiOperation("新增定时任务")
    @PostMapping("/add")
    public Boolean add(@RequestBody SysJob sysJob) {
        return jobService.insertJob(sysJob);
    }

    /**
     * 定时任务立即执行一次
     */
    @ApiOperation(value = "定时任务立即执行一次")
    @PutMapping("/run")
    public void run(@RequestBody SysJob job) {
        jobService.run(job);
    }

    /**
     * 批量删除定时任务
     */
    @ApiOperation(value = "批量删除定时任务")
    @DeleteMapping("/{jobIds}")
    public void batchRemoveJob(@PathVariable Long[] jobIds) {
        jobService.deleteJobByIds(jobIds);
    }

    /**
     * 删除定时任务
     */
    @ApiOperation(value = "删除定时任务")
    @DeleteMapping("/{jobId}")
    public Boolean removeById(@PathVariable Long jobId) throws SchedulerException {
        return jobService.deleteJobById(jobId);
    }

    /**
     * 定时任务状态修改
     */
    @ApiOperation(value = "定时任务状态修改", hidden = true)
    @PutMapping("/changeStatus")
    public Boolean changeStatus(@RequestBody SysJob job) {
        SysJob newJob = jobService.getById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return jobService.changeStatus(newJob);
    }
}
